import { useGlobalStore } from '@/store/app';

export interface RequestOptions {
	method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
	data?: any;
	headers?: Record<string, string>;
}

export function createRequest<T = any>(url: string, options: RequestOptions = {}): Promise<T> {
	const globalStore = useGlobalStore();
	const BASE_URL = 'http://192.168.1.19:8089/api';
	const TIMEOUT = 15000;

	const config = {
		method: options.method || (options.data && Object.keys(options.data).length > 0 ? 'POST' : 'GET'),
		data: options.data || {},
		headers: options.headers || {}
	};

	const fullUrl = url.startsWith('http') ? url : `${BASE_URL}${url}`;

	return new Promise<T>((resolve, reject) => {
		uni.request({
			url: fullUrl,
			method: config.method as any,
			header: {
				'Content-Type': 'application/json',
				Authorization: globalStore.userInfo?.token || '',
				...config.headers
			},
			data: config.data,
			timeout: TIMEOUT,
			success: (response: any) => {
				const { statusCode, data } = response;

				if (statusCode >= 200 && statusCode < 300) {
					if (data.code === 0 || data.code === 200 || data.success) {
						resolve(data);
					} else {
						// 处理嵌套的错误信息格式
						const errorMsg = data.data?.msg || data.msg || data.message || '业务处理失败';
						const errorCode = data.data?.code || data.code;

						const err: any = new Error(errorMsg);
						err.code = errorCode;
						err.originalData = data;
						reject(err);
					}
				} else {
					const err: any = new Error(`HTTP错误: ${statusCode}`);
					err.status = statusCode;
					reject(err);
				}
			},
			fail: (error: any) => {
				console.error('请求失败详情:', error);

				let errorMessage = '网络请求失败';
				if (error.data && error.data.msg) {
					if (error.data.msg.includes('timeout')) {
						errorMessage = '请求超时';
					} else {
						errorMessage = error.data.msg;
					}
				}

				const err: any = new Error(errorMessage);
				err.originalError = error;
				err.errMsg = error.data.msg;
				reject(err);
			}
		});
	});
}
